<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.min.css">
</head>
<body>
<main>
    <div class="post">
        <h2 class="title">新年快乐</h2>
        <p class="author">楼主：行痴</p>
        <p class="text">新的一年，祝大家新年快乐，身体健康，升职加薪！</p>
    </div>
    <div class="reply">
        <h4 class="title">发表回复</h4>
        <p class="user-box">用户名：<input type="text" class="user"></p>
        <textarea class="editor"></textarea>
        <button class="send">发表</button>
    </div>
    <div class="comments">
        <ul class="list">
            <li>
                <p class="floor">1楼</p>
                <p class="author">层主：<span class="name">小鹿</span></p>
                <p class="content">同意楼主的观点</p>
            </li>
            <li>
                <p class="floor">1楼</p>
                <p class="author">层主：<span class="name">小鹿</span></p>
                <p class="content">同意楼主的观点</p>
            </li>
        </ul>
    </div>
</main>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/template-native.min.js"></script>
<script id="item" type="text/html">
    <% for (const comment of comments) { %>
    <li>
        <p class="floor"><%=comment.id%>楼 <a class="delete" data-id="<%=comment.id%>">删除</a></p>
        <p class="author">层主：<span class="name"><%=comment.name%></span></p>
        <p class="content"><%=comment.content%></p>
    </li>
    <% } %>
</script>
<script>
  const $list = $(".comments .list");

  function getComments() {
    $.get("http://localhost:3000/comments", function (data) {
      $list.html(template("item", { comments: data }))

      $(".delete").click(function () {
        const id = $(this).attr("data-id");
        console.log("id>>", id);
        $.ajax("http://localhost:3000/comments/" + id, {
          type: "delete",
          success: function () {
            getComments();
          },
          error: function (error) {
            alert(error);
          }
        });
      });
    });
  }

  getComments();

  $(".send").click(function () {
    const name = $(".user").val();
    const content = $(".editor").val();
    if (!name || !content) {
      alert("请输入用户名和内容！");
      return;
    }
    $.post("http://localhost:3000/comments", {
      name, content,
    }, function () {
      getComments();
      $(".user").val("");
      $(".editor").val("");
    });
  });
</script>
</body>
</html>
